<?php

class Application_Model_Mapper_TurncachepunkteMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Turncachepunkte');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Turncachepunkte $turnpunkt)
	{
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
		
			$data = array(
					'id' => $generatedid,
					'turn' => $turnpunkt->getTurn(),
					'position' => $turnpunkt->getPosition(),
					'lat' => $turnpunkt->getLat(),
					'lng' => $turnpunkt->getLng(),
					'referenzid' => $turnpunkt->getReferenzid(),
					'referenzobjekt' => $turnpunkt->getReferenzobjekt(),
					'status' => $turnpunkt->getStatus(),
					'name' => $turnpunkt->getName()
			);
	
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($turnpunkt);
		}
		
	}
	
	public function addarray($turnpunkte, $turn)
	{
		for($i = 0; $i <count($turnpunkte);++$i){
			$turnpunkt = new Application_Model_Turncachepunkte();
			$turnpunkt->setLat($turnpunkte[$i]['latlng']['$a']);
			$turnpunkt->setLng($turnpunkte[$i]['latlng']['ab']);
			$turnpunkt->setPosition($turnpunkte[$i]['position']);
			$turnpunkt->setReferenzid($turnpunkte[$i]['objektid']);
			$turnpunkt->setReferenzobjekt($turnpunkte[$i]['objekttyp']);
			$turnpunkt->setName($turnpunkte[$i]['name']);
			$turnpunkt->setStatus($turnpunkte[$i]['status']);
			$turnpunkt->setTurn($turn);
			$this->add($turnpunkt);
		}
	}
	
	
	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('turncachepunkte');
		$entry->where('turncachepunkte.id = ?', $id);
		return $entry->query()->fetch();
	}

	public function fetchTurnid($turnid)
	{
 		$db = Zend_Db_Table::getDefaultAdapter();
 		$entry = new Zend_Db_Select($db);
		$entry->from('turncachepunkte');
		$entry->where('turncachepunkte.turn = ?', $turnid);
		$entry->order('position ASC');
		return $entry->query()->fetchall();
	}

}




